package me.zhengjie.config;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Component
@ConfigurationProperties(prefix = "market.info")
public class MarketInfoProperties {


    @Getter
    private List<MarketInfo> marketInfos = new ArrayList<>();

    @Data
    @AllArgsConstructor
    public static class MarketInfo {
        private String code;
        private String url;
        private String klineUrl;
    }

    public void setMarketInfos(List<MarketInfo> marketInfos) {
        this.marketInfos = marketInfos;
    }

    // 这里你需要自定义一个方法来初始化marketInfos，因为Spring Boot不会自动将单个属性映射到集合中
    @PostConstruct
    public void init() {
        String shCode = this.getCode("sh");
        String shUrl = this.getUrl("sh");
        String shKlineUrl = this.getKlineUrl("sh");
        if (shCode != null && shUrl != null && shKlineUrl != null) {
            marketInfos.add(new MarketInfo(shCode, shUrl, shKlineUrl));
        }

        String szCode = this.getCode("sz");
        String szUrl = this.getUrl("sz");
        String szKlineUrl = this.getKlineUrl("sz");
        if (szCode != null && szUrl != null) {
            marketInfos.add(new MarketInfo(szCode, szUrl, szKlineUrl));
        }
    }

    @Autowired
    private Environment environment;

    private String getCode(String type) {
        return environment.getProperty("market.info." + type + ".code");
    }

    private String getUrl(String type) {
        return environment.getProperty("market.info." + type + ".url");
    }

    private String getKlineUrl(String type) {
        return environment.getProperty("market.info." + type + ".klineUrl");
    }
}